# -*- coding: utf-8 -*-
"""
社交互动 - 视图函数
"""

from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.db import models
from .models import ActivityComment, CommentLike, ActivityRating, ActivityLike
from activities.models import Activity
import json


# ========== 评论相关API ==========

@require_http_methods(["GET"])
def api_comments_list(request, activity_id):
    """获取活动评论列表API"""
    activity = get_object_or_404(Activity, id=activity_id)
    comments = ActivityComment.objects.filter(
        activity=activity,
        parent=None  # 只获取顶级评论
    ).select_related('user').order_by('-created_at')
    
    results = []
    for comment in comments:
        results.append({
            'id': comment.id,
            'user': {
                'id': comment.user.id,
                'username': comment.user.username,
                'nickname': comment.user.nickname,
                'avatar': comment.user.avatar,
            },
            'content': comment.content,
            'images': comment.images,
            'like_count': comment.like_count,
            'created_at': comment.created_at.isoformat(),
            'replies': [{
                'id': reply.id,
                'user': {
                    'id': reply.user.id,
                    'username': reply.user.username,
                    'nickname': reply.user.nickname,
                    'avatar': reply.user.avatar,
                },
                'content': reply.content,
                'created_at': reply.created_at.isoformat(),
            } for reply in comment.replies.all()]
        })
    
    return JsonResponse({
        'code': 200,
        'data': {
            'results': results
        }
    })


@login_required
@require_http_methods(["POST"])
def api_comment_create(request, activity_id):
    """发表评论API"""
    try:
        activity = get_object_or_404(Activity, id=activity_id)
        data = json.loads(request.body)
        
        comment = ActivityComment.objects.create(
            activity=activity,
            user=request.user,
            content=data.get('content'),
            images=data.get('images', ''),
            parent_id=data.get('parent_id')
        )
        
        # 更新活动评论数
        activity.comment_count += 1
        activity.save(update_fields=['comment_count'])
        
        return JsonResponse({
            'code': 200,
            'message': '评论成功',
            'data': {
                'id': comment.id
            }
        })
        
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': f'评论失败：{str(e)}'
        }, status=500)


@login_required
@require_http_methods(["DELETE"])
def api_comment_delete(request, comment_id):
    """删除评论API"""
    try:
        comment = ActivityComment.objects.get(id=comment_id, user=request.user)
        activity = comment.activity
        
        # 删除评论
        comment.delete()
        
        # 更新活动评论数
        activity.comment_count -= 1
        activity.save(update_fields=['comment_count'])
        
        return JsonResponse({
            'code': 200,
            'message': '删除成功'
        })
        
    except ActivityComment.DoesNotExist:
        return JsonResponse({
            'code': 404,
            'message': '评论不存在'
        }, status=404)


@login_required
@require_http_methods(["POST"])
def api_comment_like(request, comment_id):
    """点赞评论API"""
    try:
        comment = get_object_or_404(ActivityComment, id=comment_id)
        
        # 检查是否已点赞
        if CommentLike.objects.filter(comment=comment, user=request.user).exists():
            return JsonResponse({
                'code': 400,
                'message': '已经点赞过了'
            }, status=400)
        
        # 创建点赞记录
        CommentLike.objects.create(
            comment=comment,
            user=request.user
        )
        
        # 更新点赞数
        comment.like_count += 1
        comment.save(update_fields=['like_count'])
        
        return JsonResponse({
            'code': 200,
            'message': '点赞成功'
        })
        
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': f'操作失败：{str(e)}'
        }, status=500)


@login_required
@require_http_methods(["POST"])
def api_comment_unlike(request, comment_id):
    """取消点赞API"""
    try:
        comment = get_object_or_404(ActivityComment, id=comment_id)
        
        # 删除点赞记录
        deleted = CommentLike.objects.filter(
            comment=comment,
            user=request.user
        ).delete()[0]
        
        if deleted > 0:
            # 更新点赞数
            comment.like_count -= 1
            comment.save(update_fields=['like_count'])
        
        return JsonResponse({
            'code': 200,
            'message': '已取消点赞'
        })
        
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': f'操作失败：{str(e)}'
        }, status=500)


# ========== 评分相关API ==========

@require_http_methods(["GET"])
def api_ratings_list(request, activity_id):
    """获取活动评分列表API"""
    activity = get_object_or_404(Activity, id=activity_id)
    ratings = ActivityRating.objects.filter(activity=activity).select_related('user').order_by('-created_at')
    
    results = [{
        'id': r.id,
        'user': {
            'id': r.user.id,
            'username': r.user.username,
            'nickname': r.user.nickname,
            'avatar': r.user.avatar,
        },
        'score': r.score,
        'organization_score': r.organization_score,
        'experience_score': r.experience_score,
        'review': r.review,
        'created_at': r.created_at.isoformat(),
    } for r in ratings]
    
    return JsonResponse({
        'code': 200,
        'data': {
            'results': results
        }
    })


@login_required
@require_http_methods(["POST"])
def api_rating_create(request, activity_id):
    """提交评分API"""
    try:
        activity = get_object_or_404(Activity, id=activity_id)
        data = json.loads(request.body)
        
        # 检查是否已评分
        if ActivityRating.objects.filter(activity=activity, user=request.user).exists():
            return JsonResponse({
                'code': 400,
                'message': '您已经评分过了'
            }, status=400)
        
        # 创建评分
        rating = ActivityRating.objects.create(
            activity=activity,
            user=request.user,
            score=data.get('score'),
            organization_score=data.get('organization_score'),
            experience_score=data.get('experience_score'),
            review=data.get('review', '')
        )
        
        # 更新活动评分统计
        activity.rating_count += 1
        total_score = (activity.rating_average * (activity.rating_count - 1) + rating.score) / activity.rating_count
        activity.rating_average = total_score
        activity.save(update_fields=['rating_count', 'rating_average'])
        
        return JsonResponse({
            'code': 200,
            'message': '评分成功'
        })
        
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': f'评分失败：{str(e)}'
        }, status=500)


# ========== 活动点赞相关API ==========

@login_required
@require_http_methods(["POST"])
def api_activity_like(request, activity_id):
    """点赞活动API"""
    try:
        activity = get_object_or_404(Activity, id=activity_id)
        
        # 检查是否已点赞
        like, created = ActivityLike.objects.get_or_create(
            activity=activity,
            user=request.user
        )
        
        if not created:
            return JsonResponse({
                'code': 400,
                'message': '已经点赞过了'
            }, status=400)
        
        # 更新活动点赞数
        activity.like_count = models.F('like_count') + 1
        activity.save(update_fields=['like_count'])
        activity.refresh_from_db()
        
        return JsonResponse({
            'code': 200,
            'message': '点赞成功',
            'data': {
                'like_count': activity.like_count
            }
        })
        
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': f'操作失败：{str(e)}'
        }, status=500)


@login_required
@require_http_methods(["POST"])
def api_activity_unlike(request, activity_id):
    """取消点赞活动API"""
    try:
        activity = get_object_or_404(Activity, id=activity_id)
        
        # 删除点赞记录
        deleted = ActivityLike.objects.filter(
            activity=activity,
            user=request.user
        ).delete()[0]
        
        if deleted > 0:
            # 更新活动点赞数
            activity.like_count = models.F('like_count') - 1
            activity.save(update_fields=['like_count'])
            activity.refresh_from_db()
        
        return JsonResponse({
            'code': 200,
            'message': '已取消点赞',
            'data': {
                'like_count': activity.like_count
            }
        })
        
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': f'操作失败：{str(e)}'
        }, status=500)


@require_http_methods(["GET"])
def api_activity_like_status(request, activity_id):
    """检查活动点赞状态API"""
    try:
        activity = get_object_or_404(Activity, id=activity_id)
        
        is_liked = False
        if request.user.is_authenticated:
            is_liked = ActivityLike.objects.filter(
                activity=activity,
                user=request.user
            ).exists()
        
        return JsonResponse({
            'code': 200,
            'data': {
                'is_liked': is_liked,
                'like_count': activity.like_count
            }
        })
        
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': f'操作失败：{str(e)}'
        }, status=500)
